package com.nacos.demo.listener;

import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.AbstractListener;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executor;

/**
 * fixme 加入此配置，貌似没有效果，配置发生改变，没有监听到
 *
 * @author hh
 * @since 2023/4/2
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class NacosCustomeConfigListener implements ApplicationRunner {

    private final ConfigService configService;

    @Value("${spring.cloud.nacos.config.group:DEFAULT_GROUP}")
    private String groupId;

    private static final String LISTENER_CONFIG = "nacos-demo-config.yml";

    // @NacosConfigListener(dataId = LISTENER_CONFIG)
    // public void onMessage(String config) {
    //     log.info("@NacosConfigListener 监控到Nacos [{}] 配置发生改变", LISTENER_CONFIG);
    // }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 添加nacos配置文件监听
        listenerNacosDatasource();
        log.info("nacos配置【{}】加入监听", LISTENER_CONFIG);
    }

    /**
     * 监听配置变化
     *
     * @throws Exception 异常
     */
    private void listenerNacosDatasource() throws Exception {
        configService.addListener(LISTENER_CONFIG, groupId, new AbstractListener() {
            @Override
            public void receiveConfigInfo(String configInfo) {
                log.info("监控到Nacos [{}] 配置发生改变", LISTENER_CONFIG);
                // TODO
            }

            @Override
            public Executor getExecutor() {
                return null;
            }
        });
    }
}
